package com.distributer.policy.service.impl;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.distributer.policy.request.PolicyAddRequest;
import com.distributer.policy.request.PolicyRefreshRequest;
import com.distributer.policy.request.PolicyUpdateRequest;
import com.distributer.policy.request.Request;
import com.distributer.policy.service.AsyncHandelerRequestService;
import com.distributer.policy.thread.RequestQueue;

@Service
public class AsyncHandelerRequestServiceImpl implements AsyncHandelerRequestService {

	private static final Logger LOGGER= LoggerFactory.getLogger(AsyncHandelerRequestServiceImpl.class);
	
	@Override
	public void process(Request request) {
		RequestQueue requestQueues = RequestQueue.instance();
		Map<String, Boolean> flagMap = requestQueues.getFlagMap();
		String jbPolicyNo = request.getJbPolicyNo();
		if (request instanceof PolicyAddRequest) {
			flagMap.put(jbPolicyNo, true);
		}
		if (request instanceof PolicyUpdateRequest) {
			flagMap.put(jbPolicyNo, true);
		}
		if (request instanceof PolicyRefreshRequest) {
			Boolean flag = flagMap.get(jbPolicyNo);
			if (flag == null) {
				flagMap.put(jbPolicyNo, false);
			}
			// 存在写请求。
			if (flag != null && flag) {
				flagMap.put(jbPolicyNo, false);
			}
			// 存在写请求，并且存在读请求，过滤掉本次读请求
			if (flag != null && !flag) {
				return;
			}
		}
		ArrayBlockingQueue<Request> queue = getReallyQuequeByJbpolicyNo(jbPolicyNo);
		queue.add(request);
	}

	public ArrayBlockingQueue<Request> getReallyQuequeByJbpolicyNo(String jbPolicyNo) {
		RequestQueue requestQueues = RequestQueue.instance();
		int queueSize = requestQueues.queueSize();
		int h;
		int hash = ((h = jbPolicyNo.hashCode()) ^ (h >>> 16));
		int index = hash & (queueSize - 1);
		LOGGER.info("钧保保单号："+ jbPolicyNo+"，选择队列索引为： "+ index);
		return requestQueues.getQueueByIndex(index);
	}
	
}
